const timeout = 5000;
const parseParam = o => {
  return Object.keys(o).map(k => k +'='+ o[k]).join('&');
};
const get = (url, param = {}, opt = {}) => {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url +'?'+ parseParam(param));
    xhr.onreadystatechange = () => {
      if (xhr.readyState !== 4) return;
      if (xhr.status === 200) {
        resolve(JSON.parse(xhr.response));
      }else{
        reject(url +' status: '+ xhr.status);
      }
    }
    xhr.timeout = opt.timeout || timeout;
    xhr.ontimeout = reject;
    xhr.onerror = reject;
    xhr.send();
  });
};
const post = (url, param = {}, opt = {}) => {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', url);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = () => {
      if (xhr.readyState !== 4 ) return;
      if (xhr.status === 200 ) {
        resolve(JSON.parse(xhr.response));
      }else{
        reject('Request status: '+ xhr.status);
      }
    }
    xhr.timeout = opt.timeout || timeout;
    xhr.ontimeout = reject;
    xhr.onerror = reject;
    param = parseParam(param);
    xhr.send(param);
  });
};
const getText = (url, param = {}, opt = {}) => {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url +'?'+ parseParam(param));
    xhr.onreadystatechange = () => {
      if (xhr.readyState !== 4) return;
      if (xhr.status === 200) {
        resolve(xhr.response);
      }else{
        reject();
      }
    }
    xhr.timeout = opt.timeout || timeout;
    xhr.ontimeout = reject;
    xhr.onerror = reject;
    xhr.send();
  });
};
let jsonpId = 0;
const jsonp = (url, param = {}) => {
  return new Promise((resolve, reject) => {
    let script = document.createElement('script');
    document.body.appendChild(script);

    // set callback name
    jsonpId++;
    param.callback = `jsonp${jsonpId++}`;

    // set callback
    window[param.callback] = data => {
      resolve(data);
      delete window[param.callback];
      document.body.removeChild(script);
    };
    script.onerror = reject;
    script.src = url +'?'+ parseParam(param);
  });
};
const getScript = (url, param = {}) => {
  return new Promise((resolve, reject) => {
    let script = document.createElement('script');
    document.body.appendChild(script);
    script.onload = resolve;
    script.onerror = reject;
    script.src = url +'?'+ parseParam(param);
  });
};

export default { get, post, jsonp, getScript, getText };
